package com.cloudcentral.controller;

import com.cloudcentral.exception.FailureException;
import com.cloudcentral.exception.InvalidException;
import com.cloudcentral.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import static com.cloudcentral.util.Utils.errorMessage;

/**
 * Create by WEI
 * 2021-08-22 22:59
 */
@Slf4j
@ControllerAdvice
public class BaseController {
  @ExceptionHandler(value = {DuplicateKeyException.class})
  public Result<String> handler(DuplicateKeyException e) {
    String message = errorMessage(e);
    log.error("{} -> {}", Result.ResultCode.DUPLICATE.getName(), message);
    return Result.duplicate(message);
  }

  @ExceptionHandler(value = {FailureException.class})
  public Result<String> handler(FailureException e) {
    String message = errorMessage(e);
    log.error("{} -> {}", Result.ResultCode.FAIL.getName(), message);
    return Result.fail(message);
  }

  @ExceptionHandler(value = {InvalidException.class})
  public Result<String> handler(InvalidException e) {
    String message = errorMessage(e);
    log.error("{} -> {}", Result.ResultCode.INVALID.getName(), message);
    return Result.invalid(message);
  }

  @ExceptionHandler(value = {Exception.class})
  public Result<String> handler(Exception e) {
    String message = errorMessage(e);
    log.error("{} -> {}", Result.ResultCode.EXCEPTION.getName(), message);
    return Result.exception(message);
  }
}